<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="70px">
      <el-row :gutter="24">
        <el-col :span="4">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadData">搜索</el-button>
          <el-button @click="searchResetForm('form')">重 置</el-button>

        </el-col>
      </el-row>
    </el-form>

    <div style="margin-bottom: 20px;">
      <el-button type="primary" size="small" @click="add('formLabelAlign')">添加</el-button>
      <el-button type="success" size="small" @click="putListed(1)">批量上架</el-button>
      <el-button type="danger" size="small"  @click="putListed(0)">批量下架</el-button>

    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="selectionChange"
    >
      <el-table-column
        type="selection"
        align="center"
      />
      <el-table-column
        label="序号"
        type="index"
        align="center"
        width="50"
      />
      <el-table-column v-for="(item,index) in columnLists" :key="index" :prop="item.prop" :label="item.label" align="center" />
      <el-table-column prop="isListed" label="是否上架" align="center" sortable>
        <template slot-scope="scope">
          <el-switch @change="changeGoodsListed(scope.$index)" v-model="scope.row.isListed" :active-value="1" :inactive-value="0"  active-color="#13ce66"  inactive-color="#ff4949"></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="edit(scope.$index)"
          >
            编辑
          </el-button>

          <el-button
            v-if="type!=='user'"
            class="del"
            type="text"
            @click="del(scope.$index)"
          >
            删除
          </el-button>





        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :current-page="pageNum" :page-size="pageSize" @handleChange="handleChange" />

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogVisible" width="45%">
      <el-form ref="formLabelAlign" :model="formLabelAlign" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品分类" prop="categoryId">
              <el-select v-model="formLabelAlign.categoryId">
                <el-option v-for="item in categoryData" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="formLabelAlign.name" clearable />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品原价" prop="originalPrice">
              <el-input v-model="formLabelAlign.originalPrice" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品现价" prop="ruingPrice">
              <el-input v-model="formLabelAlign.ruingPrice" clearable />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品库存" prop="stock">
              <el-input v-model="formLabelAlign.stock" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品规格" prop="qualityId">
              <el-select v-model="formLabelAlign.qualityId">
                <el-option v-for="item in qualityList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="封面图片" prop="image">
              <el-upload
                ref="upload"
                :headers="headers"
                class="avatar-uploader"
                :action="action"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-change="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="商品描述" prop="context">
              <quill-editor
                ref="myQuillEditor"
                v-model="formLabelAlign.context"
                :options="editorOption"
                @blur="onEditorBlur($event)"
                @focus="onEditorFocus($event)"
                @change="onEditorChange($event)"
              />            </el-form-item>
          </el-col>

        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="save('formLabelAlign')">确 定</el-button>
        <el-button size="mini" @click="resetForm('formLabelAlign')">重 置</el-button>
        <el-button size="mini" type="danger" @click="cancel('formLabelAlign')">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { showData, resetForm, validate, success, fail } from '@/api/common'
import Pagination from '@/components/Pagination'
import Column from '@/components/Column'
import { get, lists, post, del } from '@/api/requestCommon'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { getToken } from '@/utils/auth'
export default {
  name: 'PagePermission',
  components: {
    Pagination,
    quillEditor
  },
  data() {
    return {
      headers: { Authorization: getToken() },
      action: process.env.VUE_APP_BASE_API + 'file/uploadFile',
      imageUrl: '',
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            // [{'direction': 'rtl'}],                         // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            [{ font: [] }], // 字体种类
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除文本格式
            ['link', 'image', 'video'] // 链接、图片、视频
          ] // 工具菜单栏配置
        },
        placeholder: '请输入商品描述', // 提示
        readyOnly: false, // 是否只读
        theme: 'snow', // 主题 snow/bubble
        syntax: true // 语法检测
      },

      pageNum: 1, pageSize: 10, total: 0,
      form: { name: '', categoryId: '' },
      tableData: [],
      selectRows: [],
      dialogVisible: false,
      title: '添加商品名称',
      editId: '',
      columnLists: [
        { prop: 'name', label: '商品名称' },
        { prop: 'originalPrice', label: '商品原价' },
        { prop: 'ruingPrice', label: '商品现价' },
        { prop: 'stock', label: '商品库存' },

        { prop: 'categoryName', label: '商品分类' },
        { prop: 'createTime', label: '创建时间' }
      ],
      type: 'shop',
      rules: {
        ruingPrice: [
          { required: true, message: '请输入商品现价', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'change' }
        ],
        categoryId: [
          { required: true, message: '请输入商品分类', trigger: 'change' }

        ],
        image: [
          { required: true, message: '请选择封面图片', trigger: 'change', validator: (rule, value, callback) => {
            console.log('value', value)
            if (!value) {
              callback(new Error('请选择封面图片'))
            } else {
              callback()
            }
          } }

        ]
      },

      formLabelAlign: {
        id: '',
        name: '',
        categoryId: '',
        stock: '',
        context: '',
        ruingPrice: '',
        originalPrice: '',
        image: '',
        qualityId: ''
      },
      loading: true,
      categoryData: [],
      fileImage: '',
      qualityList: []

    }
  },
  created() {

  },
  mounted() {
    this.loadData()
    this.categoryList()
  },
  methods: {
      putListed(isListed){
         if (this.selectRows.length===0){
            fail('请选择数据')
            return false
         }
         const goodsList=[]
         this.selectRows.forEach((item, index) => {
           item.isListed=isListed
           goodsList.push(item)
         })
         post('goods/batchListed',goodsList).then(response=>{
           if(response.code===200){
             success(response.msg)
             this.loadData()
           }else{
             fail(response.msg)
           }
         })
      },
      changeGoodsListed(index) {
        post('goods/changeListed',{id:this.tableData[index].id,isListed:this.tableData[index].isListed}).then(response => {
          if(response.code === 200){
            success(response.msg)
          }else{
            fail(response.msg)
          }
        })

    },
    qualityData() {
      get('quality/findAll').then(res => {
        if (res.code === 200) {
          this.qualityList = res.data
        } else {
          fail(res.msg)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.imageUrl = res.data
        this.formLabelAlign.image = res.data
      }
    },
    beforeAvatarUpload(file) {

    },
    onEditorBlur() { }, // 失去焦点触发事件
    onEditorFocus() { }, // 获得焦点触发事件
    onEditorChange(event) { }, // 内容改变触发事件
    del(index) {
      this.$confirm('此操作将永久删除该商品名称, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del('goods', this.tableData[index].id).then(response => {
          if (response.code === 200) {
            success(response.msg)
            this.loadData()
          } else {
            fail(response.msg)
          }
        })
      }).catch(() => {

      })
    },
    categoryList() {
      get('goods/categoryList').then(response => {
        if (response.code === 200) {
          this.categoryData = response.data
        } else {
          fail(response.msg)
        }
      })
    },
    edit(index) {
      this.title = '编辑商品名称'
      this.dialogVisible = true
      const row = this.tableData[index]
      get('goods/findById/' + row.id).then(response => {
        if (response.code === 200) {
          Object.assign(this.formLabelAlign, response.data)
          this.imageUrl = response.data.image
        }
      })
    },
    cancel(formName) {
      resetForm(this, formName)
      this.dialogVisible = false
    },

    resetForm(formName) {
      resetForm(this, formName)
    },
    searchResetForm(formName) {
      resetForm(this, formName)
      this.loadData()
    },
    save(formName) {
      if (validate(this, formName)) {
        post('goods/save', this.formLabelAlign).then(response => {
          if (response.code === 200) {
            this.dialogVisible = false
            this.loadData()
          } else {
            fail(response.msg)
          }
        })
      }
    },
    add(formName) {
      this.title = '添加商品名称'
      this.dialogVisible = true
      this.imageUrl = ''
      this.$nextTick(() => {
        resetForm(this, formName)
      })
    },

    selectionChange(rows) {
      this.selectRows = rows
    },

    handleChange(pageNum, pageSize) {
      this.pageNum = pageNum
      this.pageSize = pageSize
      this.loadData()
    },

    loadData() {
      this.form.pageNum = this.pageNum
      this.form.pageSize = this.pageSize
      lists('goods', this.form).then(response => {
        console.log('response',response)
        showData(response, this)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.avatar-uploader  {
  border: 1px dashed #14161c;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 130px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 40px;
  color: #8c939d;
  width: 200px;
  height: 140px;
  position: absolute;
  top: 40px;
   display: block;
}
.avatar {
  width: 178px;
  height: 130px;
  display: block;
}

.avatar-uploader img{
  cursor: pointer;
  width: 200px;
  height: 130px;
}

</style>
